import Vue from "vue";
import VueRouter from "vue-router";
import routes from "./routes";
import NProgress from "nprogress";
import { notification } from "ant-design-vue";
import "nprogress/nprogress.css";
import findLast from "lodash/findLast";
import { check, isLogin } from "@/utils/auth";
Vue.use(VueRouter);

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
});

const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) {
    return originalPush.call(this, location, onResolve, onReject);
  }
  return originalPush.call(this, location).catch((err) => err);
};

router.beforeEach((to, from, next) => {
  if (to.path !== from.path) {
    NProgress.start();
  }

  // 从右向左遍历找到值
  const record = findLast(to.matched, (record) => record.meta.authority);
  // 判断是否有用户限制，没有权限则进入
  if (record && !check(record.meta.authority)) {
    // 如果没有登录且要去的页面不是login页，则跳转到登录页面，否则跳转到403
    if (!isLogin() && to.path !== "/user/login") {
      next("/user/login");
    } else if (to.path !== "/403") {
      notification.error({
        message: "403",
        description: "你没有权限访问，请联系管理员",
      });
      next("/403");
    }
    NProgress.done();
  }
  next();
});

router.afterEach(() => {
  NProgress.done();
});

export default router;
